<template>
  <div class="mesRequire-plan-pack">
    <!-- tab+列表 -->
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClickTab">
        <el-tab-pane
          :label="$i18n.t('mesRequirePlan.all')"
          name="1"
        ></el-tab-pane>
        <el-tab-pane
          :label="`${ite.name}(${ite.count})`"
          v-for="(ite, i) in statusList"
          :key="i"
          :name="ite.status"
        >
        </el-tab-pane>
      </el-tabs>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        @handleReset="handleReset"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesRequirePlanTable"
        :transFormdata="transFormdata"
        :initForm="initForm"
      >
      </ele-page>
    </div>
    <!-- 新增弹窗 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
      size="70%"
    >
      <template v-slot:customerName>
        <el-input
          v-model="formDataDialog.customerName"
          readonly
          :placeholder="$t('mesSalesOrder.selectCustomer')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="click('add')"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!-- 编辑弹窗 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="editFormDataDialog"
      v-bind="editFormDescDialog"
      :request-fn="editHandleSubmit"
      :visible.sync="editVisible"
      :title="title"
      size="30%"
    >
      <template v-slot:customerName>
        <el-input
          v-model="editFormDataDialog.customerName"
          readonly
          :placeholder="$t('mesSalesOrder.selectCustomer')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="click('edit')"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:prodName>
        <el-input
          v-model="editFormDataDialog.prodName"
          readonly
          :placeholder="$i18n.t('mesRequirePlan.pleaseSelectProduct')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="addList()"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!-- 客户列表弹窗 -->
    <ele-dialog-table
      :title="$t('mesSalesOrder.customerQuery')"
      width="800px"
      :visible.sync="mesCustomerDialogVisible"
      :formConfig="mesCustomerSearchDialog"
      :column="mesCustomerDialogColumn"
      @getSelectData="getSelectCustomer"
      :getList="getSelectCustomerList"
      :hasFooter="hasMesSalesOrderFooter"
      :maxHeight="300"
    >
    </ele-dialog-table>
    <!-- 产品弹窗 -->
    <ele-dialog-table
      :title="$i18n.t('mesRequirePlan.addProduct')"
      width="800px"
      ref="dialogTable"
      :visible.sync="goodsVisible"
      :formConfig="goodsSearchDialog"
      :column="goodsDialogColumn"
      @getSelectData="getSelectBaseGoods"
      :getList="getBaseGoodsList"
      :hasFooter="hasGoodsFooter"
      :otherParam="{ goodsTypeKey: 'CP,BCP' }"
    >
    </ele-dialog-table>
  </div>
</template>

<script>
import {
  operateList,
  searchConfig,
  addFormDialog,
  rowConfig,
  editFormDialog,
} from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  getPlanStatusList,
  apsPlanSchedule
} from "@/api/order/mesRequirePlan";
import { goodsDialog } from "./mixinGoods";
import { mesCustomerDialog } from "./mixinCustomer";
export default {
  name: "mesRequirePlan",
  components: {},
  mixins: [goodsDialog, mesCustomerDialog, addFormDialog, editFormDialog],
  data() {
    return {
      title: null,
      visible: false,
      editVisible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      editFormDataDialog: {},
      searchConfig,
      operateList,
      getList,
      importVisible: false,
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"), // 序号
          fixed: "left",
        },
        {
          prop: "requireCode",
          label: $i18n.t("mesRequirePlan.requireCode"), // 需求编码
          width: 190,
          fixed: "left",
          render: (h, { row }) => {
            return (
              <el-link onClick={() => this.goInfo(row)} type="primary">
                {row.requireCode}
              </el-link>
            );
          },
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesRequirePlan.prodCode"), // 物料编码
          minWidth: 160,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesRequirePlan.prodName"), // 物料名称
          width: 130,
        },
        {
          prop: "deliveryDate",
          label: $i18n.t("mesRequirePlan.deliveryDate"), // 交付日期
          width: 120,
        },
        {
          prop: "unit",
          label: $i18n.t("mesRequirePlan.unit"), // 计量单位名称
          width: 120,
        },
        {
          prop: "requireStatus",
          label: $i18n.t("mesRequirePlan.requireStatus"), // 需求排期状态：10待排期、20部分排期、30排期完成
          width: 110,
          fixed: "right",
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getPlanStatusList();
            return list.data.result;
          },
        },
        {
          prop: "customerName",
          label: $i18n.t("mesRequirePlan.customerName"), // 客户名称
          width: 160,
        },
        {
          prop: "quantity",
          label: $i18n.t("mesRequirePlan.quantity"), // 计划数量
          width: 100,
        },
        {
          prop: "scheduledCount",
          label: $i18n.t("mesRequirePlan.scheduledCount"), // 排产次数
          width: 100,
        },
        {
          prop: "scheduledNum",
          label: $i18n.t("mesRequirePlan.scheduledNum"), // 已排产数量
          width: 100,
        },
        {
          prop: "remark",
          label: $i18n.t("mesRequirePlan.remark"), // 备注
        },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"), // 创建人名称
          width: 140,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"), // 创建时间
          width: 180,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"), // 更新人名称
          width: 140,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"), // 更新时间
          width: 180,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"), // 操作
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
      activeName: "1",
      statusList: [],
      statusListOption: [],
      statusName: [
        $i18n.t("mesRequirePlan.pendingProduction"),
        $i18n.t("mesRequirePlan.schedulingInProgress"),
        $i18n.t("mesRequirePlan.partialScheduling"),
        $i18n.t("mesRequirePlan.scheduleCompleted"),
      ],
      initForm: {},
      customerType: "add",
    };
  },
  computed: {},
  methods: {
    async getPlanStatusList() {
      let res = await getPlanStatusList();
      this.statusListOption = res.data.result;
    },
    // 重置
    handleReset() {
      this.activeName = "1";
      this.refresh(true);
    },
    //转化表格数据
    transFormdata(data) {
      let { page: records, statusList } = data.data.result;
      statusList.map((item) => {
        let obj = this.statusListOption.find((ite) => {
          return ite.value == item.status;
        });
        item.name = obj.description;
      });
      this.statusList = statusList;
      return Promise.resolve({ ...records });
    },
    // tab切换
    handleClickTab(tab, event) {
      this.initForm =
        tab.index == 0
          ? {}
          : { requireStatus: this.statusList[tab.index - 1].status };
      this.$refs.eleTable.refresh();
    },
    addList() {
      this.goodsVisible = true;
    },
    // 客户选择弹窗
    click(type) {
      this.mesCustomerDialogVisible = true;
      this.customerType = type;
    },
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        // 排期
        scheduling: () => {
          if (data.rows[0].requireStatus == "30") {
            return this.$message.warning(
              $i18n.t(
                "mesRequirePlan.theProductionDemandPlanHasBeenScheduledToBeCompleted"
              )
            );
          }
          let queryParam = {
            id: data.rows[0].id,
          };
          let pathParam = "/order/mesRequirePlan/scheduling";
          this.$router.push({ path: pathParam, query: queryParam });
        },
         // 高级排期
         seniorScheduling: () => {
          this.$confirm(
            $i18n.t("mesRequirePlan.apsConfirm"),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.submit"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const idList = data.rows.map((val) => val.id);
            var param={
              idList:idList
            }
            this.apsPlanSchedule(param);
          });
        },
        deleteBatch: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesRequirePlan.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.submit"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
      };
      fnc[data.handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          if (row.requireStatus == 30) {
            return this.$message.warning($i18n.t("mesRequirePlan.msg2"));
          }
          this.editFormDataDialog = { ...row };
          this.editVisible = true;
        },
        detail: () => {
          this.goInfo(row);
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesRequirePlan.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.id);
          });
        },
      };
      fnc[handleName]();
    },

    // 进入详情页
    goInfo({ id, requireCode }) {
      let queryParam = {
        id,
        requireCode,
      };
      let pathParam = "/order/mesRequirePlan/details";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.editVisible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //新增弹框提交事件
    handleSubmit(data) {
      data.codeStrategy = "mesRequirePlanCode";

      if (this.isLoading) return; // 判断状态
      const params = {
        title: $i18n.t("common.addSuccess"),
        api: rowCreate,
        data: {
          ...data,
          // 重新包装数据
          mesRequirePlanList: (data.mesRequirePlanList || []).map((ite) => {
            let {
              seriesCode,
              seriesName,
              goodsName,
              goodsCode,
              unit,
              unitCode,
              deliveryDate,
              quantity,
              remark,
            } = ite;
            return {
              seriesCode,
              seriesName,
              prodCode: goodsCode,
              prodName: goodsName,
              unit,
              remark,
              unitCode,
              deliveryDate,
              quantity,
            };
          }),
        },
      };
      this.doSubmit(params);
    },
    // 编辑弹框提交事件
    editHandleSubmit(data) {
      const params = {
        title: $i18n.t("common.editSuccess"),
        api: rowUpdate,
        data,
      };

      this.doSubmit(params);
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //aps高级排程
    apsPlanSchedule(data) {
      this.loading = true;
      apsPlanSchedule(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.operateSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
  },
  
  created() {
    this.getPlanStatusList();
  },
};
</script>
<style scoped lang="scss">
.mesRequire-plan-pack {
  /deep/ .el-table__header {
    .required > div::before {
      content: "*" !important;
      color: red !important;
      margin-top: -8px;
      background: none;
    }
  }
}
</style>
